package cn.wsxiot.webdemo.controller;

import cn.wsxiot.webdemo.domain.Myfile;
import cn.wsxiot.webdemo.service.MyfileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/files")
public class MyfileController {

    @Autowired
    private MyfileService myfileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public String upload(HttpServletRequest httpServletRequest){
        String ret = "true";
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;
            MultipartFile multipartFile = multipartRequest.getFile("fcon");
            if (multipartFile.getSize() > 1073741824L) {
                ret = "文件过大，请限制在1G以内";
            }
            String filelibdir = httpServletRequest.getSession().getServletContext().getRealPath("filelib");
            File file = new File(filelibdir);
            if(!file.exists()){
                file.mkdir();
            }
            String fsname = multipartFile.getOriginalFilename();//原始文件名字
            int dotindex = fsname.lastIndexOf('.');
            String sourcetime = String.valueOf(System.currentTimeMillis());
            String fnewname = fsname.substring(0, dotindex) + "_" + sourcetime + fsname.substring(dotindex);
            File targetFile = new File(filelibdir + File.separator + fnewname);
            Myfile myfile = new Myfile(multipartRequest.getParameter("fdesc"), fsname, fnewname, targetFile.getAbsolutePath());
            if(myfileService.addmyfile(myfile) == "true"){
                multipartFile.transferTo(targetFile);
            }else{
                ret = "内部错误";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
